package pathfinding;

import impsoft.scripting.ibot.structs.AryanTile;
import pathfinding.Path.Step;
import base.DreamScript;
import base.DreamUtility;

public class PathFindingUtils extends DreamUtility {

	public PathFindingUtils(DreamScript cs) {
		super(cs);
	}

	public int getCost(boolean unreachable, AryanTile start, AryanTile goal) {
		AryanTile[] path = getPath(start, goal);
		if (path != null) {
			return path.length;
		} else {
			if (unreachable) {
				return start.distanceTo(goal);
			}

			return -1;
		}
	}

	public AryanTile[] getPath(final AryanTile start, AryanTile goal) {
		TileBasedMap map = new TileBasedMap() {

			private boolean[][] visited = new boolean[64][64];

			@Override
			public boolean blocked(Mover mover, int x, int y) {
				try {
					return !cs.theMiniMap.canReachReflection(new AryanTile(start.x - 32 + x, start.y - 32 + y));
				} catch (InterruptedException e) {
					e.printStackTrace();
					return true;
				}
			}

			@Override
			public float getCost(Mover mover, int sx, int sy, int tx, int ty) {
				return 1;
			}

			@Override
			public int getHeightInTiles() {
				return 64;
			}

			@Override
			public int getWidthInTiles() {
				return 64;
			}

			@Override
			public void pathFinderVisited(int x, int y) {
				visited[x][y] = true;
			}

		};

		try {
			if (start.distanceTo(goal) < 32) {
				AStarPathFinder finder = new AStarPathFinder(map, 500, false);
				Path path = finder.findPath(new Mover() {
				}, 32, 32, 32 + goal.x - start.x, 32 + goal.y - start.y);

				AryanTile[] aryanTilePath = new AryanTile[path.getLength()];
				for (int i = 0; i < path.getLength(); i++) {
					Step step = path.getStep(i);
					aryanTilePath[0] = new AryanTile(cs.getLocation().x + step.getX(), start.y + step.getY());
				}

				if (aryanTilePath.length > 0) {
					return aryanTilePath;
				}
			}
		} catch (Throwable t) {
			t.printStackTrace();
		}

		return null;
	}
}
